from django import forms
from django.forms.fields import IntegerField
from django.forms.models import modelformset_factory, BaseModelFormSet
from django.contrib.auth.models import User

from issues.models import Issue, Urgency, Importance, STATUS_CHOICES

__all__ = ('IssueCreateForm', 'IssueEditForm', 'SearchForm', 'IssueFormSet',)

class IssueCreateForm(forms.ModelForm):
    """
    ModelForm for an Issue, used for creation and editing
    """
    class Meta:
        model = Issue
        fields = ('summary', 'description',)

class IssueEditForm(forms.ModelForm):
    def __init__(self, *args, **kwargs):
        super(IssueEditForm, self).__init__(*args, **kwargs)
        self.initial['owners'] = ','.join([u.username for u in self.instance.owners.all()])

    owners = forms.CharField(help_text=u"Enter valid usernames for members of this project, separated by commas", required=False)

    def clean_owners(self):
        data = self.cleaned_data['owners']
        usernames = [username.strip() for username in data.split(',')]
        invalid_usernames = []
        users = []
        for username in usernames:
            user = self.instance.project.members.filter(username=username)
            if not user:
                invalid_usernames.append(username)
            else:
                users.append(user[0])
        if invalid_usernames:
            if len(invalid_usernames) > 1:
                raise forms.ValidationError("%s are invalid usernames" % ','.join(invalid_usernames))
            else:
                raise forms.ValidationError("%s is an invalid username" % invalid_usernames[0])
        return users

    class Meta:
        model = Issue

class SearchForm(forms.Form):
    """
    Allows user to search for Issues based on certain criteria, none required, most found in Issue model
    """
    keywords = forms.CharField(help_text='Keyword search of issue title and description', required=False)
    date_added = forms.DateTimeField(help_text='Date issue was created', required=False)
    date_modified = forms.DateTimeField(help_text='Date issue was last modified', required=False)
    date_completed = forms.DateTimeField(help_text='Date issue was closed', required=False)
    date_due = forms.DateTimeField(help_text='Date issue is due', required=False)
    status = forms.ChoiceField(choices=STATUS_CHOICES, required=False)
    urgency = forms.ModelChoiceField(queryset=Urgency.objects.all(), required=False)
    importance = forms.ModelChoiceField(queryset=Importance.objects.all(), required=False)
    creator = forms.ModelChoiceField(queryset=User.objects.all(), required=False)
    owner = forms.ModelChoiceField(queryset=User.objects.all(), required=False)
    stakeholder = forms.ModelChoiceField(queryset=User.objects.all(), required=False)
    
class BaseIssueFormSet(BaseModelFormSet):
    def add_fields(self, form, index):
        """Add a NON-hidden field for the object's primary key."""
        from django.db.models import AutoField
        self._pk_field = pk = self.model._meta.pk
        if pk.auto_created or isinstance(pk, AutoField):
            form.fields[self._pk_field.name] = IntegerField(required=False)
        super(BaseModelFormSet, self).add_fields(form, index)

IssueFormSet = modelformset_factory(Issue, formset=BaseIssueFormSet, can_delete=True)